<?php

class Silk_Qslb_Block_Product_List extends Mage_Catalog_Block_Product_Abstract
{
	private $_currentCategory = null;
	private $_total = 0;
	private $_collection;

	public function getCurrentCategory()
	{
		if($this->_currentCategory) return $this->_currentCategory;

		$id = $this->getRequest()->getParam('id',12);
		$this->_currentCategory = Mage::getModel('catalog/category')->load($id);
		return $this->_currentCategory;
	}

	public function getProductCollection($limit = null)
	{
		$query = Mage::helper('catalogsearch')->getQuery();

		if($this->_collection) return $this->_collection;

		$curPage = $this->getRequest()->getParam('page',1);
		$brand = $this->getRequest()->getParam('brand');

		$dir = $this->getRequest()->getParam('dir','desc');
		
		if(!$limit)
		{
			$limit = 12;
		}
		$attributes = array('name','sku','price','special_price','small_image','status','thumbnail','image','brand','promotion');

		$collection = Mage::getResourceModel('catalog/product_collection');
		$collection->addAttributeToSelect($attributes)
			->addStoreFilter(Mage::app()->getStore()->getId())
			->addCategoryFilter($this->getCurrentCategory())
			->addAttributeToFilter('visibility', array(
                'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
            ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));


        $collection->getSelect()->
            joinLeft('sales_flat_order_item AS sfoi',
            'e.entity_id = sfoi.product_id',
            'SUM(sfoi.qty_ordered) AS ordered_qty')->group('e.entity_id')->order('ordered_qty ' . $dir);
        

		// if($this->getRequest()->getParam('order') !== "bestseller")
		// {
		// 	$collection = Mage::getResourceModel('catalog/product_collection');
		// 	$collection->addAttributeToSelect($attributes)
		// 		->addStoreFilter(Mage::app()->getStore()->getId())
		// 		->addCategoryFilter($this->getCurrentCategory())
		// 		->addAttributeToFilter('visibility', array(
	 //                'neq' => Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE))
	 //            ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));

		// }else{
		// 	$_featcategory = $this->getCurrentCategory();
		// 	$visibility = array(
		// 		Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
		// 		Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
		// 	$storeId = Mage::app()->getStore()->getId();
		// 	$collection = Mage::getResourceModel('reports/product_collection')
		// 		->addAttributeToSelect($attributes)
		// 		->addOrderedQty()
		// 		->addCategoryFilter($_featcategory)
		// 		->setOrder('ordered_qty', $dir);
		// }

		if($brand)
		{
			$collection->addAttributeToFilter('brand', array('eq'=>$brand));
		}

		if($query->getQueryText())
		{
			$collection->addAttributeToFilter('name', array('like' => '%' . $query->getQueryText() . '%'));
		}
		
		$isShowOutOfStock = Mage::getStoreConfigFlag('cataloginventory/options/show_out_of_stock');
        if(!$isShowOutOfStock)
        {
        	Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($collection);
        }
        
        $originCollection = clone $collection;

        $collection->setCurPage($curPage)->setPageSize($limit);

        $brands = $this->_getAvailableBrands($originCollection);
        $this->setBrands($brands);
        $this->_collection = $collection;

        return $collection;
	}

	/**
     * @param Mage_Catalog_Model_Resource_Product_Collection $collection
     * @return array
     */
    protected function _getAvailableBrands(Mage_Catalog_Model_Resource_Product_Collection $collection)
    {
        $attributeCode = 'brand';
        $brandsValue = array_unique($collection->getColumnValues($attributeCode));
        $attributeModel = Mage::getSingleton('eav/config')
            ->getAttribute('catalog_product', $attributeCode)->getSource();

        $brands = array();
        foreach ($brandsValue as $brand) {
            $brands[] = array(
                'id' => $brand,
                'name' => $attributeModel->getOptionText($brand),
            );
        }

        return $brands;
    }

    public function getBrandName($id)
    {
    	$attributeModel = Mage::getSingleton('eav/config')
            ->getAttribute('catalog_product', 'brand')->getSource();
        return $attributeModel->getOptionText($id);
    }

	public function getKeyword()
	{
		$query = Mage::helper('catalogsearch')->getQuery();
		return $query->getQuery_text();
	}

	public function getPagerHtml($limit = 12)
	{
		$params = array();
		$params['id'] = $this->getCurrentCategory()->getId();
		$curPage = $this->getRequest()->getParam('page',1);
		$params['page'] = 1;
		$params['limit'] = $this->getRequest()->getParam('limit',12);
		$params['brand'] = $this->getRequest()->getParam('brand');
		$searchKetWord = Mage::helper('catalogsearch')->getQuery();
		$path = 'catalog/category/view';

		if ($searchKetWord->getQueryText()) {
			$path = 'catalogsearch/result/index';
			$params['q'] = $searchKetWord->getQueryText();
		}


		$start = 0;
		$end = 0;

		$totalPage = $this->getProductCollection()->getLastPageNumber();


		if($curPage<=5)
		{
			$start = 1;
			if($totalPage <= 8)
			{
				$end = $totalPage;
			}
			else
			{
				$end = 8;
			}
		}
		if($curPage > 5)
		{
			if($totalPage <= 8)
			{
				$start = 1;
				$end = $totalPage;
			}

			if($totalPage > 8)
			{
				$end = $curPage + 3;
				if($end > $totalPage) 
				{
					$end = $totalPage;
					$start = $totalPage - 7;
				}
				else
				{
					$start = $curPage - 4;
				}
			}
		}

		// $params['page'] = 1;
		// $searchKetWord = Mage::helper('catalogsearch')->getQuery();
		// if($searchKetWord->getQueryText())
		// {
		// 	$keyWord = $searchKetWord->getQueryText();
		// 	$path = 'catalogsearch/result/?';

		// 	$html = '<li class="first"><a href="'.$this->getUrl($path).'">首页</a></li>';
		// 	if($curPage>1)
		// 	{
		// 		$params['page'] = $curPage-1;
		// 		$html .= '<li class="first"><a href="'.$this->getUrl().''.$path.'page='.$params['page'].'&'.'limit='.$params['limit'].'&'.'q='.$keyWord.'">上一页</a></li>';
		// 	}

		// 	for($i = $start; $i <= $end; $i++)
		// 	{
		// 		$class = "";
		// 		if($curPage==$i) $class="class='active'";
		// 		$params['page'] = $i;
		// 		$url = $this->getUrl().''.$path.'page='.$params['page'].'&'.'limit='.$params['limit'].'&'.'q='.$keyWord;
		// 		$html .= "<li {$class}><a href='{$url}'>{$i}</a></li>";
		// 	}

		// 	if($curPage<$totalPage)
		// 	{
		// 		$params['page'] = $curPage+1;
		// 		$html .= '<li class="last"><a href="'.$this->getUrl().''.$path.'page='.$params['page'].'&'.'limit='.$params['limit'].'&'.'q='.$keyWord.'">下一页</a></li>';
		// 	}
		// 	$params['page'] = $totalPage;
		// 	$html .= '<li class="last"><a href="'.$this->getUrl().''.$path.'page='.$params['page'].'&'.'limit='.$params['limit'].'&'.'q='.$keyWord.'">尾页</a></li>';
		// 	return $html;
		// }

		$html = '<li class="first"><a href="'.$this->getUrl($path,$params).'">首页</a></li>';
		if($curPage>1)
		{
			$params['page'] = $curPage-1;
			$html .= '<li class="first"><a href="'.$this->getUrl($path,$params).'">上一页</a></li>';
		}

		for($i = $start; $i <= $end; $i++)
		{
			$class = "";
			if($curPage==$i) $class="class='active'";
			$params['page'] = $i;
			$url = $this->getUrl($path,$params);
			$html .= "<li {$class}><a href='{$url}'>{$i}</a></li>";
		}

		if($curPage<$totalPage)
		{
			$params['page'] = $curPage+1;
			$html .= '<li class="last"><a href="'.$this->getUrl($path,$params).'">下一页</a></li>';
		}
		$params['page'] = $totalPage;
		$html .= '<li class="last"><a href="'.$this->getUrl($path,$params).'">尾页</a></li>';
		return $html;
	}

	public function getAvailableOrders()
    {
        return [
            [
                'name'=> '销量',
                'url' => 'dir=asc&order=bestseller',
            ],
        ];
    }

    public function getAvailableLimit($cataId)
    {
		$keyword = $this->getRequest()->getParam('q');
		if ($keyword)
		{
			$path = 'catalogsearch/result/index';
		} else {
			$path = 'catalog/category/view';
		}
		$params = array(
			'id' => $this->getRequest()->getParam('id', 12),
			'brand' => $this->getRequest()->getParam('brand'),
			'q' => $keyword,
			'limit' => 12
		);


		$limits = array();
		$limits[] = array(
			'limit' => 12,
			'url' => $this->getUrl($path, $params)
		);

		$params['limit'] = 24;
		$limits[] = array(
			'limit' => 24,
			'url' => $this->getUrl($path, $params)
		);

		$params['limit'] = 36;
		$limits[] = array(
			'limit' => 36,
			'url' => $this->getUrl($path, $params)
		);

		return $limits;
    }

    public function getCurrentDirection($cataId)
    {
		$keyword = $this->getRequest()->getParam('q');
		if ($keyword) {
			$path = 'catalogsearch/result/index';
		} else {
			$path = 'catalog/category/view';
		}
		$params = array(
			'limit' => $this->getRequest()->getParam('limit'),
			'id' => $this->getRequest()->getParam('id', 12),
			'brand' => $this->getRequest()->getParam('brand'),
			'q' => $keyword
		);

        if($this->getRequest()->getParam('dir') == 'desc')
        {
			$params['dir'] = 'asc';
            return [
                'dir' => 'desc',
				'url' => $this->getUrl($path, $params),
                'title'=> '设置降序顺序',
            ];
        }else{
			$params['dir'] = 'desc';
            return [
                'dir' => 'asc',
				'url' => $this->getUrl($path, $params),
                'title'=> '设置升序顺序',
            ];
        }
    }

	/*Get Layer for Catagory*/
	public function getLayerForCatagory($cataId)
	{
		if($cataId !== 12 && $cataId)
		{
			$currenCatagory = Mage::getModel('catalog/category')->load($cataId);
			return $currenCatagory->getParentCategory();
		}else{
			return NULL;
		}
	}

	/*Get First Page New Product*/
	public function getNewProductForOne()
	{
		$_newProductCollection = Mage::getModel('catalog/product')->getCollection()
            ->setPage(1,4)
            ->setOrder("entity_id")
            ->addAttributeToSelect('*');
		Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($this->_newProductCollection);
		Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_newProductCollection);
		Mage::getSingleton('cataloginventory/stock')->addInStockFilterToCollection($_newProductCollection);
		$_newProductCollection->getSelect()->group('e.entity_id');
		return $_newProductCollection;
	}
}